<?php

namespace app\api\logic;

use think\facade\Db;
use think\facade\Log;
use app\api\service\Common;
use app\admin\model\Algorithm as AlgorithmModel;


class ProductMergeLogic
{

    protected $refresh = false;

    public function __construct()
    {
        $this->refresh = env('ENV_REFRESH_CACHE', false);
    }

    /**
     * @describe 从缓存获取产品数据
     * @author: Bobo
     * @date: 2025-04-25 14:19:15 
     */
    public function getProductsFromCache()
    {
        return (new CacheLogic())->getAllProducts($this->refresh);
    }

    /**
     * @describe // 处理文字搜索条件
     * @author: Bobo
     * @date: 2025-05-20 14:28:25 
     * @param [type] @required
     * @return Renderable
     */
    public function processNameFilters(array  &$where)
    {
        // 查找算法ID 
        if (isset($where['algorithm_name']) && !empty($where['algorithm_name'])) {
            $algorithmModel = new AlgorithmModel();
            $algorithmList = (array)$algorithmModel->getAttributes('algorithm');
            $algorithmListLower = array_map('strtolower', $algorithmList);
            $algorithmNameInputLower = strtolower($where['algorithm_name']);
            $algorithmId = array_search($algorithmNameInputLower, $algorithmListLower);
            if ($algorithmId !== false && is_numeric($algorithmId) && $algorithmId > 0) {
                $where['algorithm'] = (int) $algorithmId; // 赋值算法ID并确保是整数
            }
            unset($where['algorithm_name']);
        }

        // 查找品牌ID
        if (isset($where['brand_name']) && !empty($where['brand_name'])) {
            $brandId = $this->findIdByNameFromTable('db_product_brand', $where['brand_name']);
            if ($brandId) $where['brand'] = $brandId;
            unset($where['brand_name']);
        }

        // 查找配件ID
        if (isset($where['accessory_name']) && !empty($where['accessory_name'])) {
            $accessoryId = $this->findIdByNameFromTable('db_product_category', $where['accessory_name']);
            if ($accessoryId) $where['accessory'] = $accessoryId;
            unset($where['accessory_name']);
        }

        // 查找币种ID
        if (isset($where['coin_name']) && !empty($where['coin_name'])) {
            $coinId = $this->findIdByNameFromTable('db_product_currency', $where['coin_name'], 'name_short');
            if ($coinId) $where['coin'] = $coinId;
            unset($where['coin_name']);
        }


        // 查找解决方案ID
        if (isset($where['solution_name']) && !empty($where['solution_name'])) {
            $solutionId = $this->findIdByNameFromTable('db_product_category', $where['solution_name']);
            if ($solutionId) $where['solution'] = $solutionId;
            unset($where['solution_name']);
        }
    }


    /**
     * 根据名称从指定的数据库表中查找对应的ID（不区分大小写）
     *
     * @param string $tableName 数据库表名
     * @param string $nameValue 要查找的名称值
     * @return int|null 找到的ID，或null
     */
    private function findIdByNameFromTable(string $tableName, string $nameValue, string $fieldValue = 'name'): ?int
    {
        if (empty($nameValue)) {
            return null;
        }
        // 将输入名称转换为小写进行比较
        $nameLower = strtolower($nameValue);

        $rawSql = "SELECT `id` FROM `$tableName` WHERE LOWER(`$fieldValue`) = ? AND `is_del` = ? LIMIT 1";
        $result = Db::query($rawSql, [$nameLower, 0]);

        return !empty($result) ? (int) $result[0]['id'] : null; // 强制转换为 int
    }

    /**
     * @describe 应用过滤条件
     * @author: Bobo
     * @date: 2025-04-25 14:19:15 
     */
    public function applyFilters(array $list, array $where, int $role): array
    {
        $data = [];

        // 名称搜索过滤
        if (!empty($where['name'])) {
            $list = array_filter($list, function ($item) use ($where) {
                return mb_stripos($item['productname'], $where['name']) !== false;
            });
        }
        // 类型过滤
        if (!empty($where['type'])) {
            $list = array_filter($list, function ($item) use ($where) {
                return $item['type'] == $where['type'];
            });
        }


        foreach ($list as $value) {

            if ($value['inventory_type'] == -1 && !$value['max_price']) {
                $value['max_price'] = $value['estimate_price'];
            }
            if ($value['inventory_type'] == -1 && !$value['min_price']) {
                $value['min_price'] = $value['estimate_price'];
            }
            if ($value['inventory_type'] == -1 && !$value['max_first_discount_price']) {
                $value['max_first_discount_price'] = $value['estimate_price'];
            }
            if ($value['inventory_type'] == -1 && !$value['min_first_discount_price']) {
                $value['min_first_discount_price'] = $value['estimate_price'];
            }

            // 最低价格检查
            if (!empty($where['min_price']) && $where['min_price'] > 0) {
                $compareMaxPrice = $role == 2 ? $value['max_first_discount_price'] : $value['max_price'];
                if (empty($compareMaxPrice) || $where['min_price'] > $compareMaxPrice) {
                    continue;
                }
            }
            // 最高价格检查
            if (!empty($where['max_price']) && $where['max_price'] > 0) {
                $compareMinPrice = $role == 2 ? $value['min_first_discount_price'] : $value['min_price'];
                if (empty($compareMinPrice) || $where['max_price'] < $compareMinPrice) {
                    continue;
                }
            }



            $productData = [
                'id' => $value['id'],
                'name' => $value['productname'],
                'urlname' => $value['producturlname'],
                'image' => $value['main_photo'][0]['url'] ?? '',
                'max_price' => (float) $value['max_price'] ?? '',
                'min_price' => (float) $value['min_price'] ?? '',
                'max_first_discount_price' => (float) $value['max_first_discount_price'] ?? '',
                'min_first_discount_price' => (float) $value['min_first_discount_price'] ?? '',
                'hashrate' => $value['hashrate'] ?? '',
                'power' => $value['power'] ?? '',
                'inventory_type' => $value['inventory_type'] ?? '',
                'inventory_type_text' => $value['inventory_type_text'] ?? '',
                'describe' => $value['describe'] ?? '',
                'type' => (int)$value['type'] ?? '',
                'primary_brand' => $value['primary_brand'] ?? '--',
                'sort' => $value['sort'] ?? 0,
            ];

            // 应用其他过滤条件
            if ($this->shouldAddProduct($value, $where, $productData)) {
                $data[] = $productData;
            }
        }

        return $data;
    }

    /**
     * @describe 判断是否应该添加产品
     * @author: Bobo
     * @date: 2025-04-25 14:19:15 
     */
    public function shouldAddProduct(array $value, array $where, array $productData): bool
    {
        $filterConditions = [
            'brand' => 'brand',
            'accessory' => 'accessory',
            'algorithm' => 'algorithm',
            'coin' => 'coin',
            'solution' => 'solution'
        ];

        // 检查是否需要过滤
        $needFilter = false;
        foreach ($filterConditions as $whereKey => $valueKey) {
            if (!empty($where[$whereKey]) && $where[$whereKey] > 0) {
                $needFilter = true;
                break;
            }
        }

        if (!$needFilter) {
            return true;
        }

        // 检查过滤条件
        foreach ($filterConditions as $whereKey => $valueKey) {
            if (!empty($where[$whereKey]) && $where[$whereKey] > 0) {
                $fieldValues = isset($value[$valueKey]) ? (array)$value[$valueKey] : [];
                if (in_array($where[$whereKey], $fieldValues)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * @describe 应用排序
     * @author: Bobo
     * @date: 2025-04-25 14:19:15 
     */
    public function applySorting(array &$data, array $where): void
    {
        if (empty($where['sort'])) {
            return;
        }
        $sortMap = [
            '1' => fn($a, $b) => $a['sort'] - $b['sort'], // 按sort升序排序
            '2' => function ($a, $b) {
                $data = array_filter([$a, $b], fn($item) => !empty($item['min_price']));
                if (empty($data)) return 0;
                $priceA = is_numeric($a['min_price']) ? (float)$a['min_price'] : 0;
                $priceB = is_numeric($b['min_price']) ? (float)$b['min_price'] : 0;
                return $priceA - $priceB;
            }, // 按最低价格升序排序
            '3' => function ($a, $b) {
                $data = array_filter([$a, $b], fn($item) => !empty($item['max_price']));
                if (empty($data)) return 0;
                $priceA = is_numeric($a['max_price']) ? (float)$a['max_price'] : 0;
                $priceB = is_numeric($b['max_price']) ? (float)$b['max_price'] : 0;
                return $priceB - $priceA;
            }, // 按最高价格降序排序
        ];

        if (isset($sortMap[$where['sort']])) {
            usort($data, $sortMap[$where['sort']]);
        }
    }

    /**
     * @describe 获取价格范围
     * @author: Bobo
     * @date: 2025-04-25 14:19:15 
     */
    public function getPriceRange(array $data): array
    {
        $max_prices = array_filter(array_column($data, 'max_price'));
        $min_prices = array_filter(array_column($data, 'min_price'));
        $max_first_discount_prices = array_filter(array_column($data, 'max_first_discount_price'));
        $min_first_discount_prices = array_filter(array_column($data, 'min_first_discount_price'));

        return [
            'max_price' => !empty($max_prices) ? max($max_prices) : null,
            'min_price' => !empty($min_prices) ? min($min_prices) : null,
            'max_first_discount_price' => !empty($max_first_discount_prices) ? max($max_first_discount_prices) : null,
            'min_first_discount_price' => !empty($min_first_discount_prices) ? min($min_first_discount_prices) : null
        ];
    }

    /**
     * @describe 分页处理
     * @author: Bobo
     * @date: 2025-04-25 14:19:15 
     */
    public function paginateData(array $data, int $page, int $page_size): array
    {
        $total = count($data);
        $offset = ($page - 1) * $page_size;

        return [
            'list' => array_slice($data, $offset, $page_size),
            'total' => $total,
            'page' => $page,
            'page_size' => $page_size,
            'total_page' => ceil($total / $page_size)
        ];
    }

    /**
     * @describe 翻译
     * @author: Bobo
     * @date: 2025-05-16 11:26:08 
     * @param [type] @required
     * @return Renderable
     */
    public function translateListData($data, $lang)
    {
        // if (strtolower($lang) === 'en') {
        //     return $data;
        // }
        if ($data['total'] == 0) {
            return $data;
        }
        try {
            $data['list'] = array_map(function ($item) {
                $item['translate_key'] = md5($item['name']);
                return $item;
            }, $data['list']);
            $data['list'] = array_column($data['list'], null, 'translate_key');

            // 修复JSON格式问题
            $translateContent = [];
            foreach ($data['list'] as $key => $value) {
                $translateContent[$value['translate_key']] = $value['name'];
            }

            $translateService = new Common();
            $translateParams = [
                'content' => json_encode($translateContent),
                'target_language' => $lang
            ];

            $translateResult = $translateService->translate($translateParams);
            if (0 == $translateResult['code'] && !empty($translateResult['data'])) {
                foreach ($translateResult['data'] as $key => $value) {
                    $key = trim($key, '"');
                    if (isset($data['list'][$key])) {
                        $data['list'][$key]['name'] = $value;
                    }
                }
            } else {
                Log::error('翻译失败,translateParams:' . json_encode($translateParams) . ',translateResult:' . json_encode($translateResult));
            }
            $data['list'] = array_values($data['list']);
            return $data;
        } catch (\Exception $e) {
            $errorMessage = sprintf(
                '翻译失败,translateParams:%s,error:%s',
                isset($translateParams) ? json_encode($translateParams) : '未生成',
                $e->getMessage()
            );
            Log::error($errorMessage);
            $data['list'] = array_values($data['list']);
            return $data;
        }
    }
}
